const https = require("https");
const { existsSync, readFileSync, createReadStream } = require("fs");
const { resolve } = require("path");

const options = {
  key: readFileSync(resolve(__dirname, "key.pem")),
  cert: readFileSync(resolve(__dirname, "cert.pem")),
};

https
  .createServer(options, (req, res) => {
    const fileName = resolve(__dirname, `.${req.url}`);

    res.setHeader("Access-Control-Allow-Origin", "*");
    // 允许的header类型
    res.setHeader("Access-Control-Allow-Headers", "content-type");
    // 跨域允许的请求方式
    res.setHeader(
      "Access-Control-Allow-Methods",
      "DELETE,PUT,POST,GET,OPTIONS"
    );
    // 允许缓存1000秒
    res.setHeader("Cache-Control", "max-age=1000");

    // if (req.headers["cache-control"] === 'xxx') {
    //   console.log("Etag协商缓存命中.....");
    //   res.statusCode = 304;
    //   res.end();
    //   return;
    // }

    // 判断本地文件是否存在
    if (existsSync(fileName)) {
      const stream = createReadStream(fileName);
      stream.pipe(res);
    } else {
      res.writeHead(404, { "Content-Type": "text/plain" });
      res.write("THE RESOURCE NOT FOUND", "utf-8");
    }
  })
  .listen(8001);
